import { defineComponent, reactive, ref, toRefs } from 'vue'
import {
  NInput,
  NForm,
  NFormItem,
  NModal,
  FormRules,
  NRadioGroup,
  NRadio,
  NSpace,
  NSelect,
  NTreeSelect
} from 'naive-ui'
import { createUserReq } from '@/service/modules/user'
import { Response } from '@/service/modules/common/types'
import { renderMultipleSelectTag } from '@/common/common'
import { useRole } from '../common/use-role'
import { useDepartment } from '@/views/department/tab/department-manage-tab/use-department'

const CreateUserModal = defineComponent({
  name: 'CreateUserModal',
  props: {
    showModal: {
      type: Boolean,
      default: false
    }
  },
  emits: ['modalShowChange', 'refreshList'],
  setup() {
    const state = reactive({
      userInfoForm: {
        username: '',
        nickname: '',
        sex: 0,
        mobile: '',
        email: '',
        roleId: '',
        roleIds: [],
        departmentId: null
      },
      positiveButtonDisabled: ref(false),
      rules: {
        username: {
          trigger: ['input', 'blur'],
          required: true,
          validator() {
            if (state.userInfoForm.username === '') {
              return new Error(window.$t('user.usernameTips'))
            }
          }
        },
        email: {
          trigger: ['input', 'blur'],
          required: true,
          validator() {
            if (state.userInfoForm.email === '') {
              return new Error(window.$t('user.emailTips'))
            }
          }
        },
        roleIds: {
          trigger: ['input', 'blur'],
          required: true,
          validator() {
            if (state.userInfoForm.roleIds.length === 0) {
              return new Error(window.$t('user.roleIdTips'))
            }
          }
        },
        departmentId: {
          trigger: ['input', 'blur'],
          required: true,
          validator() {
            if (!state.userInfoForm.departmentId) {
              return new Error(window.$t('user.departmentTips'))
            }
          }
        }
      } as FormRules
    })
    //系统角色下拉选项
    const { roleVariables, getRoleOptions } = useRole()
    getRoleOptions(0)
    //部门树下拉选项
    const { departmentVariables, getDepartmentOptions } = useDepartment()
    getDepartmentOptions()
    return {
      ...toRefs(state),
      roleVariables,
      departmentVariables
    }
  },
  methods: {
    async onPositiveClick() {
      //输入框存在为空时则确认按钮无效
      if (
        this.userInfoForm.username === '' ||
        this.userInfoForm.email === '' ||
        this.userInfoForm.roleIds.length === 0 ||
        !this.userInfoForm.departmentId
      ) {
        return
      }
      //提交创建用户请求
      this.positiveButtonDisabled = true
      this.userInfoForm.roleId = this.userInfoForm.roleIds.join(',')
      const res: Response<any> = await createUserReq({
        ...this.userInfoForm
      }).catch(() => {
        this.positiveButtonDisabled = false
      })
      if (res.resp_code === 0) {
        this.initData()
        this.$emit('modalShowChange', false)
        this.$emit('refreshList')
        this.positiveButtonDisabled = false
      } else {
        this.positiveButtonDisabled = false
      }
    },
    onNegativeClick() {
      this.initData()
      this.$emit('modalShowChange', false)
    },
    initData() {
      this.userInfoForm.username = ''
      this.userInfoForm.nickname = ''
      this.userInfoForm.sex = 0
      this.userInfoForm.mobile = ''
      this.userInfoForm.email = ''
      this.userInfoForm.roleId = ''
      this.userInfoForm.roleIds = []
      this.userInfoForm.departmentId = null
    }
  },
  render() {
    return (
      <NModal
        show={this.showModal}
        mask-closable={false}
        style='width: 400px'
        title={window.$t('user.createUser')}
        bordered={false}
        size='huge'
        preset='dialog'
        positive-text={window.$t('dialog.positiveText')}
        negative-text={window.$t('dialog.negativeText')}
        onPositiveClick={this.onPositiveClick}
        onNegativeClick={this.onNegativeClick}
        positiveButtonProps={{
          disabled:
            this.positiveButtonDisabled ||
            this.userInfoForm.username === '' ||
            this.userInfoForm.email === '' ||
            this.userInfoForm.roleIds.length === 0 ||
            !this.userInfoForm.departmentId
        }}
        onClose={this.onNegativeClick}
      >
        <NForm
          rules={this.rules}
          label-placement='left'
          require-mark-placement='right-hanging'
          label-width='auto'
        >
          <NFormItem path='username' label={window.$t('user.username')}>
            <NInput
              type='text'
              v-model={[this.userInfoForm.username, 'value']}
              placeholder={window.$t('user.usernameTips')}
              autofocus
            />
          </NFormItem>
          <NFormItem path='nickname' label={window.$t('user.nickname')}>
            <NInput
              type='text'
              v-model={[this.userInfoForm.nickname, 'value']}
              placeholder={window.$t('user.nicknameTips')}
            />
          </NFormItem>
          <NFormItem path='sex' label={window.$t('user.sex')}>
            <NRadioGroup
              v-model={[this.userInfoForm.sex, 'value']}
              name='sexGroup'
            >
              <NSpace>
                <NRadio value={0}>{window.$t('user.man')}</NRadio>
                <NRadio value={1}>{window.$t('user.woman')}</NRadio>
              </NSpace>
            </NRadioGroup>
          </NFormItem>
          <NFormItem path='mobile' label={window.$t('user.mobile')}>
            <NInput
              type='text'
              v-model={[this.userInfoForm.mobile, 'value']}
              placeholder={window.$t('user.mobileTips')}
            />
          </NFormItem>
          <NFormItem path='email' label={window.$t('user.email')}>
            <NInput
              type='text'
              v-model={[this.userInfoForm.email, 'value']}
              placeholder={window.$t('user.emailTips')}
            />
          </NFormItem>
          <NFormItem path='roleIds' label={window.$t('user.roles')}>
            <NSelect
              v-model={[this.userInfoForm.roleIds, 'value']}
              multiple
              options={this.roleVariables.roleOptions}
              render-tag={renderMultipleSelectTag}
            />
          </NFormItem>

          <NFormItem path='departmentId' label={window.$t('user.department')}>
            <NTreeSelect
              v-model={[this.userInfoForm.departmentId, 'value']}
              options={this.departmentVariables.departmentOptions}
              label-field='name'
              key-field='id'
              children-field='subs'
              clearable
              size='small'
              placeholder={window.$t('user.departmentTips')}
            />
          </NFormItem>
        </NForm>
      </NModal>
    )
  }
})

export default CreateUserModal
